package com.example.androidproject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.androidproject.databinding.ActivityRecordBinding;
import com.example.androidproject.sqlite.UserRepository;

public class RecordActivity extends AppCompatActivity {

   private ActivityRecordBinding binding;
   private UserRepository userRepository;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      binding = ActivityRecordBinding.inflate(getLayoutInflater());
      setContentView(binding.getRoot());
      userRepository = new UserRepository(this);

      binding.loginButton.setOnClickListener(v -> login());
      binding.registerButton.setOnClickListener(v -> openRegisterActivity());
   }

   private void login() {
      String username = binding.username.getText().toString().trim();
      String password = binding.password.getText().toString().trim();

      if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
         Toast.makeText(this, "账号和密码不能为空", Toast.LENGTH_SHORT).show();
         return;
      }

      boolean isValid = userRepository.validateUser(username, password);

      if (isValid) {
         SharedPreferences sharedPreferences = getSharedPreferences("userinfo", Context.MODE_PRIVATE);
         SharedPreferences.Editor editor = sharedPreferences.edit();
         editor.putString("username", username);
         editor.apply();

         Intent intent = new Intent(this, MainActivity.class);
         startActivity(intent);
         finish();
      } else {
         Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
      }
   }

   private void openRegisterActivity() {
      Intent intent = new Intent(this, RegisterActivity.class);
      startActivityForResult(intent, 0);
   }
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);

      if (requestCode == 0 && resultCode == RESULT_OK) {
         String username = data.getStringExtra("username");
         String password = data.getStringExtra("password");

         if (username != null) {
            binding.username.setText(username);
            binding.password.setText(password);
         }
      }
   }
}
